//
//  BIDEditPhoneViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/22.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDEditPhoneViewController.h"
#import <SMS_SDK/SMSSDK.h>

static NSString *editPhoneURL = @"memberAndroid/modifyTel.action";
//验证手机号是否已注册
static NSString *checkPhoneIsExistURL = @"mobile/checkMemberIsExist.action";

@interface BIDEditPhoneViewController ()
{
    NSTimer *_timer;
    NSInteger _totalSecond;
}
@end

@implementation BIDEditPhoneViewController
@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"修改手机号";
    _totalSecond = COUNTDOWN;
    _phoneTF.inputAccessoryView = self.toolBar;
    _verifyCodeTF.inputAccessoryView = self.toolBar;
    _verifyCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    //
    NSDictionary *userInfoDic = [AppDelegate getUserDetailInfo];
    _remarksLabel.text = [[NSString alloc] initWithFormat:@"当前手机号：%@，绑定新手机号后，下次登录可使用新手机号登录", userInfoDic[@"telephone"]];
    //
    [_verifyCodeBtn setTitleColor:RGBACOLOR(27.f, 193.f, 166.f, 1.f) forState:UIControlStateNormal];
    [_verifyCodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveHandler)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)saveHandler
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], editPhoneURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&searchParam.telephone=%@", [AppDelegate getUserId], _phoneTF.text];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showAlertView:@"手机号修改成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
        }
    }];
}

- (void)alertViewHandler
{
    [delegate editPhone:_phoneTF.text];
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 获取验证码

 @param sender <#sender description#>
 */
- (IBAction)verifyCodeBtnHandler:(id)sender
{
    [_phoneTF resignFirstResponder];
    NSString *strPhoneNumber = _phoneTF.text;
    if(strPhoneNumber.length > 0)
    {
        //验证手机号格式是否正确
        BOOL isCorrect = [BIDGlobalMethods isMobilePhoneNumberHaveCorrectFormat:strPhoneNumber];
        if(isCorrect)
        {
            //验证手机号是否已经存在,不能绑定已注册过的手机号
            NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], checkPhoneIsExistURL];
            NSString *strPost = [[NSString alloc] initWithFormat:@"member.userName=%@", strPhoneNumber];
            self.bManualHandleHTTPFailed = YES;
            [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
                if(errMsg)
                {
                    //已注册
                    [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                }
                else
                {
                    //未注册，可以发送手机验证码
                    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:strPhoneNumber zone:@"86" customIdentifier:nil result:^(NSError *error){
                        if(!error)
                        {
                            [_verifyCodeBtn setEnabled:NO];
                            _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
                            [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                            [self showHint:@"验证码已发送"];
                        }
                        else
                        {
                            NSString *strError = [[NSString alloc] initWithFormat:@"%@", error];
                            [self showAlertView:strError buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
                        }
                    }];
                }
            }];
        }
        else
        {
            [self showAlertView:@"请输入有效的手机号码" buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
        }
    }
    else
    {
        [self showAlertView:@"请填写手机号码" buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
    }
}

- (void)timerFireMethod:(NSTimer*)timer
{
    _totalSecond--;
    if(_totalSecond==0)
    {
        _totalSecond = 60;
        [_timer invalidate];
        [_verifyCodeBtn setEnabled:YES];
        [_verifyCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    else
    {
        NSString *str = [[NSString alloc] initWithFormat:@"%ld秒后可重新获取", (long)_totalSecond];
        [_verifyCodeBtn setTitle:str forState:UIControlStateDisabled];
    }
}


@end
